import os
import json
import uuid
from datetime import datetime

HISTORY_PATH = os.path.expanduser("~/.video-downloader/history.json")

def load_history():
    if not os.path.exists(HISTORY_PATH):
        return []
    with open(HISTORY_PATH, "r", encoding="utf-8") as f:
        return json.load(f)

def save_history(history):
    os.makedirs(os.path.dirname(HISTORY_PATH), exist_ok=True)
    with open(HISTORY_PATH, "w", encoding="utf-8") as f:
        json.dump(history, f, ensure_ascii=False, indent=4)

def add_download_task(url, save_path="", tool="auto", status="queued", retry_count=0, progress="0%", speed="0 KB/s", tag="other", title="", author="", description="", video_id=None, fingerprint=None):
    history = load_history()
    new_task = {
        "id": str(uuid.uuid4()),
        "url": url,
        "save_path": save_path,
        "tool": tool,
        "status": status,
        "retry_count": retry_count,
        "progress": progress,
        "speed": speed,
        "tag": tag,
        "title": title,
        "author": author,
        "description": description,
        "video_id": video_id,
        "fingerprint": fingerprint,
        "time": datetime.now().isoformat()
    }
    history.insert(0, new_task)
    save_history(history)
    return new_task["id"]

def update_task_status(task_id, status):
    history = load_history()
    for task in history:
        if task["id"] == task_id:
            task["status"] = status
            if status == "failed":
                task["retry_count"] = task.get("retry_count", 0) + 1
            break
    save_history(history)

def update_task_progress(task_id, progress, speed):
    history = load_history()
    for task in history:
        if task["id"] == task_id:
            task["progress"] = progress
            task["speed"] = speed
            break
    save_history(history)

def update_task_metadata(task_id, metadata):
    history = load_history()
    for task in history:
        if task["id"] == task_id:
            task.update(metadata)
            break
    save_history(history)

def update_task_fingerprint(task_id, fingerprint):
    history = load_history()
    for task in history:
        if task["id"] == task_id:
            task["fingerprint"] = fingerprint
            break
    save_history(history)

def is_duplicate_video(video_id):
    if not video_id:
        return False
    history = load_history()
    return any(task.get("video_id") == video_id for task in history)

def is_duplicate_fingerprint(fingerprint):
    if not fingerprint:
        return False
    history = load_history()
    return any(task.get("fingerprint") == fingerprint for task in history)